var SelectAreaModal = {
  inited: false,
  callback: $.noop,

  init: function() {
    if (SelectAreaModal.inited) {
      $('#select_area_modal').modal({ show: true });
      return;
    }

    var cityMap = {};
    for (var i = 0; i < cities.length; i++) {
      cityMap[cities[i].name] = cities[i].id;
    }
    $('#city_table td').each(function() {
      var name = $.trim($(this).text());
      if (!$(this).hasClass('caption_letter') && name) {
        $(this).attr('area_id', cityMap[name]);
      }
    });

    var selectAreaModal = $('#select_area_modal');

    selectAreaModal.on('shown', function() {
      SelectAreaModal.callback = selectAreaModal.data('callback') || $.noop;
    }).modal({ show: true });

    $('#select_industry_modal_close').on('click', function() {
      SelectAreaModal._selectArea(null);
    });

    $('#select_industry_modal_any').on('click', function() {
      SelectAreaModal._selectArea([ 0, '不限' ]);
    });

    $('.area_table td').mouseenter(function() {
      if (!$(this).hasClass('caption_letter') && $.trim($(this).text())) {
        $(this).addClass('hl');
      }
    }).mouseleave(function() {
      $(this).removeClass('hl');
    });

    $('td[province_id]').click(function(event) {
      var id = $(this).attr('province_id');
      $('#province' + id).show().offset({ left: event.pageX - 200, top: event.pageY - 20 });
    });

    console.info($('.sub_area_table').length);
    $('.sub_area_table').mouseleave(function() {
      $(this).hide();
    }).insertAfter(selectAreaModal);
    console.info($('.sub_area_table').length);

    $('td[area_id]').click(function() {
      $('.sub_area_table').hide();
      SelectAreaModal._selectArea([ $(this).attr('area_id'), $(this).text() ]);
    });

    SelectAreaModal.inited = true;
  },

  _selectArea: function(value) {
    $('#select_area_modal').modal('hide');
    SelectAreaModal.callback(value);
  }
};
